#-*- coding: utf-8 -*-
#!/usr/bin/python3

import redis

class redis_handler(object):
    '''
    redis 操作
    '''
    def __init__(self, host, port, password):
        self.host = host
        self.port = port
        self.password = password

    def redis_conn(self):
        '''
        redis 连接
        '''
        r = redis.StrictRedis(host=self.host, port=self.port, password=self.password)
        return r

    def check_ttl(self, no_ttl_file):
        '''
        查找redis中所有ttl为-1的
        '''
        redis_conn = self.redis_conn()
        no_ttl_num = 0
        keys_num = redis_conn.dbsize()
        with open(no_ttl_file, 'a') as f:
            for key in redis_conn.scan_iter(count=1000):
                if redis_conn.ttl(key) == -1:
                    no_ttl_num += 1
                    f.write(str(key) + "\n")
                else:
                    continue

    def match_check_ttl(self, match_list=None):
        '''
        查找指令的redis key 查看ttl是否为-1
        '''
        redis_conn = self.redis_conn()
        if match_list is not None:
            for key_pattern in match_list:
                #遍历列表
                for key in redis_conn.scan_iter(match=key_pattern, count=1000):
                    if redis_conn.ttl(key) == -1:
                        print("正在清理 %s ....." % format(key))
                        redis_conn.delete(key)
            else:
                print("匹配key均有过期时间......")

if __name__ == '__main__':
    redis_handler = redis_handler("r-gs5oum48he84mgtgpl.redis.singapore.rds.aliyuncs.com", "6379", "FLRedis2019")
    #redis_handler.match_check_ttl(match_list=["free:chat:videopairchat:time:*", "free:chat:rec:flag:*", "match:chat:videopairchat:time:*", "match:chat:rec:flag:*", "user:match:user:info:*", "live:guest:earn:gifts:*", "user:video:pair:pullrtmpurl:info:*",  "user:card:usercounts:*", "touser:receive:card:counts:*"]) 
    #redis_handler.match_check_ttl(match_list=["room:check:count:*"])
    redis_handler.check_ttl("/data/scripts/no_ttl_file.txt")

